package com.jiudengnile.liushu.web.common.valves;

import javax.servlet.http.HttpSession;

import wint.lang.convert.ConvertUtil;
import wint.lang.utils.StringUtil;
import wint.mvc.flow.InnerFlowData;
import wint.mvc.pipeline.PipelineContext;
import wint.mvc.pipeline.valves.AbstractValve;

import com.jiudengnile.liushu.biz.constants.SessionAttributes;
import com.jiudengnile.liushu.common.request.RequestUser;
import com.jiudengnile.liushu.common.request.RequestUserHolder;

public class RequestUserHolderValve extends AbstractValve {

	@Override
	public void invoke(PipelineContext pipelineContext, InnerFlowData innerFlowData) {
		HttpSession session = innerFlowData.getSession();
		try {
			trySetRequestUser(session);
			pipelineContext.invokeNext(innerFlowData);
		} finally {
			clearRequestUser();
		}
	}
	
	private void clearRequestUser() {
		RequestUserHolder.remove();
	}
	
	private void trySetRequestUser(HttpSession session) {
		String userNick = (String)session.getAttribute(SessionAttributes.USER_NICK);
		RequestUser requestUser = new RequestUser();
		RequestUserHolder.setRequestUser(requestUser);
		
		if (userNick == null) {
			// 没有已经登陆的用户
			// TODO 可以尝试从cookie中去加载
			return;
		}
		requestUser.setUserNick(userNick);
		
		Long userId = getLoginUserId(session);
		if (userId == null || userId == 0L) {
			// 没有登陆的情况
			return;
		}
		requestUser.setUserId(userId);
	}

	private Long getLoginUserId(HttpSession session) {
		Object userIdValue = session.getAttribute(SessionAttributes.USER_ID);
		if (userIdValue == null) {
			return null;
		}
		String userIdStr = userIdValue.toString();
		if (StringUtil.isEmpty(userIdStr)) {
			return null;
		}
		if (userIdStr == "0") {
			return null;
		}
		return ConvertUtil.toLong(userIdStr, 0L);
	}
	
}
